//
//  OptionsViewController.m
//  TestApplication
//
//  Created by Hanlingyu on 16/9/21.
//  Copyright © 2016年 ltq. All rights reserved.
//

#import "OptionsViewController.h"
#import "TAMacro.h"
#import "RegisteAndLoginViewController.h"
@interface OptionsViewController ()
<
    UITableViewDelegate,
    UITableViewDataSource
>

@property (nonatomic, strong) UITableView *optionsTableView;

@end

@implementation OptionsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 27, 30, 30)];
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [self.backView addSubview:backButton];
    [backButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.optionsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    _optionsTableView.backgroundColor = [UIColor whiteColor];
    _optionsTableView.delegate = self;
    _optionsTableView.dataSource = self;
    [self.view addSubview:_optionsTableView];
    [_optionsTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (indexPath.row == 0) {
        cell.textLabel.text = @"清除缓存";

    } else {
        cell.textLabel.text = @"退出登录";
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        // 清除缓存
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        CGFloat caches = [self floatWithPath:cachePath];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清除缓存" message:[NSString stringWithFormat:@"缓存大小%.2fM",caches] preferredStyle:UIAlertControllerStyleAlert];
        [self.navigationController presentViewController:alert animated:YES completion:^{}];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self removeCache];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}]];
    } else if (indexPath.row == 1) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        //移除UserDefaults中存储的用户信息
        [userDefaults removeObjectForKey:@"user"];
        [userDefaults synchronize];
        NSLog(@"%@", [userDefaults objectForKey:@"user"]);
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[RegisteAndLoginViewController alloc] init]];
    }
}

// 删除缓存
- (void)removeCache {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    
    for (NSString *p in files) {
        NSString *path = [NSString stringWithFormat:@"%@/%@", cachePath, p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        }
    }
    
    
}


// 计算清除的缓存大小
- (CGFloat)floatWithPath:(NSString *)path {
    CGFloat num = 0;
    NSFileManager *man = [NSFileManager defaultManager];
    
    if ([man fileExistsAtPath:path]) {
        NSEnumerator *childFile = [[man subpathsAtPath:path] objectEnumerator];
        NSString *fileName;
        while ((fileName = [childFile nextObject]) != nil) {
            NSString *fileSub = [path stringByAppendingPathComponent:fileName];
            num += [self fileSizeAtPath:fileSub];
        }
    }
    return num / (1024.0 * 1024.0);
}

//计算单个文件大小
- (long long)fileSizeAtPath:(NSString *)file {
    NSFileManager *man = [NSFileManager defaultManager];
    if ([man fileExistsAtPath:file]) {
        return [[man attributesOfItemAtPath:file error:nil] fileSize];
    }
    return 0;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
